const config = require('../util/config')
const formatDate = require('../../lib/formatDate')
const logger = require('log4js').getLogger()

module.exports = (req, res) => {
    require('../util/service').handlePost(req, res, async (reqObj, resolve) => {
        if (!reqObj.page) {
            resolve({
                result: -1,
                msg: '缺少page'
            })
            return;
        }
        if (!reqObj.customer_phone) {
            resolve({
                result: -1,
                msg: '缺少customer_phone'
            })
            return;
        }
        req.session.admin.getCustomerBill = req.session.admin.getCustomerBill || {}
        req.session.admin.getCustomerBill[reqObj.customer_phone] = req.session.admin.getCustomerBill[reqObj.customer_phone] || [{}]
        req.session.admin.getCustomerBill[reqObj.customer_phone][0].createTime = formatDate(new Date())
        if (!req.session.admin.getCustomerBill[reqObj.customer_phone][reqObj.page - 1]) {
            resolve({
                result: 1,
                bills: []
            })
            return
        }
        getBills({
            customer_phone: reqObj.customer_phone,
            createTime: req.session.admin.getCustomerBill[reqObj.customer_phone][reqObj.page - 1].createTime,
            count: 10
        }).then(result => {
            if (result.length >= 10) {
                req.session.admin.getCustomerBill[reqObj.customer_phone][reqObj.page] = req.session.admin.getCustomerBill[reqObj.customer_phone][reqObj.page] || {}
                req.session.admin.getCustomerBill[reqObj.customer_phone][reqObj.page].createTime = (result[result.length - 1].createTime || result[result.length - 1].orderDate || result[result.length - 1].orderTimeStr)
            }
            resolve({
                result: 1,
                bills: result
            })
        }, result => {
            resolve({
                result: -1,
                msg: result
            })
        })
    })
}

function getBills(obj) {
    const mongoMng = require('../mng/mongoMng')
    if (!mongoMng.db) {
        logger.error('[' + __filename + ':' + __line + ']', 'mongo未连接')
        return new Promise((resolve, reject) => {
            reject('系统错误')
        })
    }
    // logger.debug('['+  __filename + ':' + __line+']', JSON.stringify(obj)
    if (obj.count <= 0) {
        return new Promise(resolve => {
            resolve([])
        })
    }
    var promise0 = new Promise((resolve, reject) => {
        var query = {
            taobaoTradeParentId: {
                $ne: null
            },
            createTime: {
                $lt: obj.createTime
            }
        }
        if (obj.customer_phone != '*') {
            query.customer_phone = obj.customer_phone == 'null' ? null : obj.customer_phone
        }
        mongoMng.db.collection('bill').find(query).sort({
            createTime: -1
        }).limit(1).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject('系统错误')
                return
            }
            resolve(result)
        })
    })
    var promise1 = new Promise((resolve, reject) => {
        var query = {
            orderId: {
                $ne: null
            },
            orderDate: {
                $lt: obj.createTime
            }
        }
        if (obj.customer_phone != '*') {
            query.customer_phone = obj.customer_phone == 'null' ? null : obj.customer_phone
        }
        mongoMng.db.collection('bill').find(query).sort({
            orderDate: -1
        }).limit(1).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject('系统错误')
                return
            }
            resolve(result)
        })
    })
    var promise2 = new Promise((resolve, reject) => {
        var query = {
            orderId: {
                $ne: null
            },
            orderTimeStr: {
                $lt: obj.createTime
            }
        }
        if (obj.customer_phone != '*') {
            query.customer_phone = obj.customer_phone == 'null' ? null : obj.customer_phone
        }
        mongoMng.db.collection('bill').find(query).sort({
            orderTimeStr: -1
        }).limit(1).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject('系统错误')
                return
            }
            resolve(result)
        })
    })
    var promise3 = new Promise((resolve, reject) => {
        var query = {
            orderId: {
                $ne: null
            },
            orderTime: {
                $lt: new Date(obj.createTime).getTime(),
                $ne: 0
            }
        }
        if (obj.customer_phone != '*') {
            query.customer_phone = obj.customer_phone == 'null' ? null : obj.customer_phone
        }
        mongoMng.db.collection('bill').find(query).sort({
            orderTime: -1
        }).limit(1).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject('系统错误')
                return
            }
            resolve(result)
        })
    })
    var promise4 = new Promise((resolve, reject) => {
        var query = {
            tradeParentId: {
                $ne: null
            },
            tkCreateTime: {
                $lt: obj.createTime
            }
        }
        if (obj.customer_phone != '*') {
            query.customer_phone = obj.customer_phone == 'null' ? null : obj.customer_phone
        }
        mongoMng.db.collection('bill').find(query).sort({
            tkCreateTime: -1
        }).limit(1).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject('系统错误')
                return
            }
            resolve(result)
        })
    })
    return new Promise((resolve, reject) => {
        Promise.all([promise0, promise1, promise2, promise3, promise4]).then(result => {
            // logger.debug('['+  __filename + ':' + __line+']', JSON.stringify(result))
            var createTime = '1970-01-01 00:00:00'
            if (result[0].length != 0 && result[0][0].createTime > createTime) {
                createTime = result[0][0].createTime
            }
            if (result[1].length != 0 && result[1][0].orderDate > createTime) {
                createTime = result[1][0].orderDate
            }
            if (result[2].length != 0 && result[2][0].orderTimeStr > createTime) {
                createTime = result[2][0].orderTimeStr
            }
            if (result[3].length != 0 && formatDate(new Date(result[3][0].orderTime)) > createTime) {
                createTime = formatDate(new Date(result[3][0].orderTime))
            }
            if (result[4].length != 0 && result[4][0].tkCreateTime > createTime) {
                createTime = result[4][0].tkCreateTime
            }
            var createTimeInt = new Date(createTime).getTime()
            var query = {
                $or: [{
                    taobaoTradeParentId: {
                        $ne: null
                    },
                    createTime: createTime
                }, {
                    orderId: {
                        $ne: null
                    },
                    orderDate: createTime
                }, {
                    orderId: {
                        $ne: null
                    },
                    orderTimeStr: createTime
                }, {
                    orderId: {
                        $ne: null
                    },
                    orderTime: {
                        $gte: createTimeInt,
                        $lt: createTimeInt + 1000
                    }
                }, {
                    tradeParentId: {
                        $ne: null
                    },
                    tkCreateTime: createTime
                }]
            }
            if (obj.customer_phone != '*') {
                query.customer_phone = obj.customer_phone == 'null' ? null : obj.customer_phone
            }
            mongoMng.db.collection('bill').find(query).toArray((err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    reject('系统错误')
                    return
                }
                var bills = []
                result.forEach(item => {
                    if (item.tradeParentId) {
                        bills.push({
                            auctionTitle: item.itemTitle,
                            createTime: item.tkCreateTime,
                            feeString: Math.round(item.pubSharePreFee * config.returnRate * 100) / 100,
                            earningTime: item.tkEarningTime,
                            returnTime: item.returnTime,
                            returnMoney: item.returnMoney,
                            auctionNum: item.itemNum,
                            exShopTitle: item.sellerShopTitle,
                            payStatus: item.tkStatus,
                            shop: 'taobao',
                            tradeParentId: item.tradeParentId,
                            itemId: item.itemId
                        })
                    } else if (item.taobaoTradeParentId) {
                        bills.push({
                            auctionTitle: item.auctionTitle,
                            createTime: item.createTime,
                            feeString: Math.round(parseFloat(item.feeString) * config.returnRate * 100) / 100,
                            earningTime: item.earningTime,
                            returnTime: item.returnTime,
                            returnMoney: item.returnMoney,
                            auctionNum: item.auctionNum,
                            exShopTitle: item.exShopTitle,
                            payStatus: item.payStatus,
                            shop: 'taobao',
                            taobaoTradeParentId: item.taobaoTradeParentId,
                            auctionId: item.auctionId
                        })
                    } else if (item.orderId) {
                        var auctionTitle = ''
                        item.skus && item.skus.forEach(item => {
                            auctionTitle += item.skuName + ';'
                        })
                        item.unionOrderMegerDetailReportSkuVos && item.unionOrderMegerDetailReportSkuVos.forEach(item => {
                            auctionTitle += item.skuName + ';'
                        })
                        var feeString = 0
                        item.skuList && item.skuList.forEach(item => {
                            auctionTitle += item.skuName + ';'
                            feeString += item.actualFee || item.estimateFee
                        })
                        auctionTitle = auctionTitle.substring(0, auctionTitle.length - 1)
                        let payStatus = 0
                        if (item.orderStatus) {
                            if (item.orderStatus == 1) {
                                payStatus = 3
                            }
                        } else if (item.validCode) {
                            if (item.validCode == 17 || item.validCode == 18) {
                                payStatus = 3
                            }
                        }
                        bills.push({
                            auctionTitle: auctionTitle,
                            createTime: item.orderDate || item.orderTimeStr || formatDate(new Date(item.orderTime)),
                            feeString: Math.round(parseFloat(item.commission ? item.commission : feeString) * config.returnRate * 100) / 100,
                            earningTime: item.finishDate || item.finishTimeStr || formatDate(new Date(item.finishTime)),
                            returnTime: item.returnTime,
                            returnMoney: item.returnMoney,
                            auctionNum: '1',
                            exShopTitle: '京东',
                            payStatus: payStatus,
                            shop: 'jd',
                            orderId: item.orderId
                        })
                    }
                })
                if (bills.length == 0) {
                    resolve(bills)
                } else {
                    getBills({
                        customer_phone: obj.customer_phone,
                        createTime: createTime,
                        count: obj.count - result.length
                    }).then(result => {
                        bills.push.apply(bills, result)
                        resolve(bills)
                    }, result => {
                        reject(result)
                    })
                }
            })
        })
    })
}